<template>
  <div class="channel-edit">
    <van-cell :border='false'>
      <div slot="title"
        class="title-text">我的频道</div>
      <van-button class="edit-btn"
        type='danger'
        plain
        round
        size='mini'
        @click="isEdit = !isEdit">{{isEdit?'保存':'编辑'}}</van-button>
    </van-cell>
    <van-grid class="my-grid"
      :gutter="10">
      <van-grid-item class="grid-item"
        v-for="value,ind in myChannels"
        :key="ind"
        @click="onMyChannelClick(value,ind)">
        <van-icon slot="icon"
          name='clear'
          v-show="isEdit && !fiexChannels.includes(value.id)">
        </van-icon>
        <span slot="text"
          class="text"
          :class="{ active: ind === active}">{{value.name}}
        </span>
      </van-grid-item>
    </van-grid>
    <!-- 频道推荐 -->
    <van-cell :border='false'>
      <div slot="title"
        class="title-text">频道推荐</div>
    </van-cell>
    <van-grid class="recommend-grid"
      :gutter="10">
      <van-grid-item class="grid-item"
        v-for="obj,ind in recommendChannel"
        :key="ind"
        icon="plus"
        :text="obj.name"
        @click="addChannel(obj)" />
    </van-grid>
  </div>
</template>

<script>
import { getAllChannel, addUserChannel, deleteUserChannel } from '@/api/channel.js'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'

export default {
  // 组件名称
  name: 'ChannelEdit',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {
    myChannels: {
      type: Array,
      required: true
    },
    active: {
      type: Number,
      required: true
    }
  },
  // 组件状态值
  data () {
    return {
      allChannel: [],
      isEdit: false,
      fiexChannels: [0]
    }
  },
  // 计算属性
  computed: {
    ...mapState(['user']),
    recommendChannel () {
      const channels = []
      this.allChannel.forEach(channel => {
        const ret = this.myChannels.find(myChannels => {
          return myChannels.id === channel.id
        })
        if (!ret) {
          channels.push(channel)
        }
      })
      return channels
    }
  },
  // 侦听器
  watch: {},
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
* 组件实例创建完成，属性已绑定，但DOM还未生成，el属性还不存在
*/
  created () {
    this.loadAllChannel()// 获取所有的频道
  },
  /**
* el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
* 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
*/
  mounted () { },
  // 组件方法
  methods: {
    async loadAllChannel () {
      try {
        const { data } = await getAllChannel()
        // console.log(data.data.channels)
        this.allChannel = data.data.channels
      } catch (err) {
        this.$toast('获取失败' + err)
        // console.log('获取失败' + err)
      }
    },

    async addChannel (obj) { // 频道添加
      this.myChannels.push(obj)
      // 数据持久化
      // 登录
      if (this.user) {
        try {
          await addUserChannel({
            id: obj.id,
            seq: this.myChannels.length
          })
        } catch (err) {
          this.$toast('保存失败请稍后重试')
        }
      } else {
        // 未登录
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    // 删除切换频道模块
    onMyChannelClick (val, ind) {
      if (this.isEdit) { // 编辑状态删除频道
        if (this.fiexChannels.includes(val.id)) {
          return
        }
        if (ind <= this.active) {
          this.$emit('updata-active', this.active - 1, true)
        }
        this.myChannels.splice(ind, 1)
        this.deleChannel(val)
      } else {
        // 非编辑状态切换频道
        this.$emit('updata-active', ind, false)
      }
    },
    async deleChannel (val) { // 删除频道模块
      try {
        if (this.user) { // 登陆时的删除
          await deleteUserChannel(val.id)
        } else { // 未登录时的删除
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (err) {
        console.log(err)
        this.$toast('发生未知错误')
      }
    }
  }
}
</script>

<style scoped lang="less">
.channel-edit {
  padding: 85px 0;
  .title-text {
    font-size: 32px;
    color: #333;
  }
  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }
  /deep/.grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 28px;
        color: #222;
        margin-top: 0;
      }
      .active {
        color: red;
      }
      .van-grid-item__icon-wrapper {
        position: unset;
      }
    }
  }
  /deep/.my-grid {
    .grid-item {
      .van-icon-clear {
        position: absolute;
        right: -10px;
        top: -10px;
        font-size: 30px;
        color: #cacaca;
        z-index: 2;
      }
    }
  }
  /deep/.recommend-grid {
    .grid-item {
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 28px;
          margin-right: 6px;
        }
      }
    }
  }
}
</style>
